<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学校官网</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <header>
        <div class="logo">
            <img src="images/logo.png" alt="校徽">
            <h1>珠海科技学院</h1>
        </div>
        <nav>
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="about.html">学校概况</a></li>
                <li><a href="academics.html">院系专业</a></li>
                <li><a href="admission.html">招生就业</a></li>
                <li><a href="research.html">科研创新</a></li>
                <li><a href="campus.html">校园生活</a></li>
            </ul>
        </nav>
    </header>

    <main>
        <section class="banner">
            <img src="images/campus.jpg" alt="校园风光">
            <div class="banner-text">
                <h2>追求卓越，创造未来</h2>
                <p>培养具有全球竞争力的高素质人才</p>
            </div>
        </section>

        <section class="news">
            <h2>新闻公告</h2>
            <div class="news-list">
                <article>
                    <h3>2025级新生开学典礼隆重举行</h3>
                    <p class="date">2025-09-01</p>
                    <p>校长在典礼上发表重要讲话，勉励新生追求卓越...</p>
                </article>
                <article>
                    <h3>我校科研成果获省级奖励</h3>
                    <p class="date">2025-08-25</p>
                    <p>计算机学院团队研究成果荣获科技进步一等奖...</p>
                </article>
            </div>
        </section>
        <div class="qa-button-container">
            <button class="qa-button" id="qa-trigger">智能问答</button>
        </div>
        <div class="qa-button-container">
            <button class="qa-button" onclick="openQAModal()">智能问答</button>
        </div>
    </main>

    <div id="qa-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>智能问答助手</h2>
                <span class="close" onclick="closeQAModal()">&times;</span>
            </div>
            <div id="qa-chat" class="chat-container"></div>
            <div class="input-area">
                <input type="text" id="qa-input" placeholder="请输入您的问题...">
                <button class="send-btn" onclick="askQuestion()">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M22 2L11 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M22 2L15 22L11 13L2 9L22 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
            </div>
            <div class="modal-footer">
                <small>由DeepSeek提供技术支持</small>
            </div>
        </div>
    </div>

    <div id="qa-modal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeQAModal()">&times;</span>
            <h2>DeepSeek 智能问答</h2>
            <button onclick="clearHistory()" class="clear-btn">清空对话历史</button>
            <div id="qa-chat"></div>
            <input type="text" id="qa-input" placeholder="输入您的问题...">
            <button onclick="askQuestion()">提问</button>
        </div>
    </div>

    <script>
        function openQAModal() {
            console.log('openQAModal called');
            const modal = document.getElementById('qa-modal');
            if (modal) {
                modal.style.display = 'block';
                console.log('Modal should be visible now');
            } else {
                console.error('QA modal element not found');
            }
        }

        function closeQAModal() {
            const modal = document.getElementById('qa-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        }

        async function askQuestion() {
            const question = document.getElementById('qa-input').value;
            if (!question) return;
            
            const chatDiv = document.getElementById('qa-chat');
            chatDiv.innerHTML += `<div class="user-question">${question}</div>`;
            
            try {
                chatDiv.innerHTML += `<div class="ai-loading">思考中...</div>`;
                const response = await getDeepSeekResponse(question);
                document.querySelector('.ai-loading').remove();
                chatDiv.innerHTML += `<div class="ai-answer">${response}</div>`;
            } catch (error) {
                document.querySelector('.ai-loading').remove();
                chatDiv.innerHTML += `<div class="ai-error">服务暂时不可用</div>`;
                console.error('问答出错:', error);
            }
            chatDiv.scrollTop = chatDiv.scrollHeight;
        }

        async function getDeepSeekResponse(question) {
            const apiKey = 'sk-02482392a3ec48be80a7df279d674b0f';
            const apiUrl = 'https://api.deepseek.com/v1/chat/completions';
            
            console.log('[Debug] 开始API调用，问题:', question);
            
            // 验证输入
            if (!question || typeof question !== 'string') {
                console.error('[Error] 无效的问题输入:', question);
                return "请输入有效的问题";
            }

            // 准备请求数据
            const requestData = {
                model: "deepseek-chat",
                messages: [{ role: "user", content: question }],
                temperature: 0.7,
                max_tokens: 1000,
                stream: false
            };

            console.log('[Debug] 请求数据:', JSON.stringify(requestData, null, 2));

            try {
                // 显示API调用开始时间
                const startTime = Date.now();
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                console.log(`[Debug] API响应时间: ${Date.now() - startTime}ms`);
                console.log('[Debug] 响应状态:', response.status);

                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('[Error] API错误详情:', errorText);
                    try {
                        const errorData = JSON.parse(errorText);
                        console.error('[Error] 解析后的错误:', errorData);
                        return `请求失败: ${errorData.error?.message || '未知错误'}`;
                    } catch (e) {
                        console.error('[Error] 解析错误响应失败:', e);
                        return `请求失败: ${response.status} ${response.statusText}`;
                    }
                }

                const data = await response.json();
                console.log('[Debug] 完整API响应:', data);
                
                if (!data.choices || !data.choices[0]?.message?.content) {
                    console.warn('[Warning] 异常API响应结构:', data);
                    return "未收到有效回答，请联系管理员。";
                }
                
                return data.choices[0].message.content;
            } catch (error) {
                console.error('[Error] API调用异常:', error);
                return `服务暂时不可用: ${error.message}`;
            }
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                console.log(`[Debug] API响应时间: ${Date.now() - startTime}ms`);
                console.log('[Debug] 响应状态:', response.status);
            
            console.log('[Debug] 开始API调用，问题:', question);
            
            // 验证输入
            if (!question || typeof question !== 'string') {
                console.error('[Error] 无效的问题输入:', question);
                return "请输入有效的问题";
            }

            // 准备请求数据
            const requestData = {
                model: "deepseek-chat",
                messages: [{ role: "user", content: question }],
                temperature: 0.7,
                max_tokens: 1000,
                stream: false
            };

            console.log('[Debug] 请求数据:', JSON.stringify(requestData, null, 2));
            
            // 添加对话历史支持
            const chatHistory = JSON.parse(localStorage.getItem('qa_history') || '[]');
            chatHistory.push({ role: "user", content: question });
            
            // 限制历史记录长度
            if (chatHistory.length > 10) {
                chatHistory.shift();
            }
            
            try {
                console.log('准备调用DeepSeek API，问题:', question);
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: chatHistory,
                        temperature: 0.7,
                        max_tokens: 1000,
                        stream: false
                    })
                });

                console.log('收到API响应状态:', response.status);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('[Error] API错误详情:', errorText);
                    try {
                        const errorData = JSON.parse(errorText);
                        console.error('[Error] 解析后的错误:', errorData);
                        return `请求失败: ${errorData.error?.message || '未知错误'}`;
                    } catch (e) {
                        console.error('[Error] 解析错误响应失败:', e);
                        return `请求失败: ${response.status} ${response.statusText}`;
                    }
                }
                
                const data = await response.json();
                console.log('完整API响应:', data);
                
                if (!data.choices || !data.choices[0]?.message?.content) {
                    console.warn('异常API响应结构:', data);
                    return "未收到有效回答，请联系管理员。";
                }
                
                // 保存AI回复到历史记录
                const aiResponse = data.choices[0].message.content;
                chatHistory.push({ role: "assistant", content: aiResponse });
                localStorage.setItem('qa_history', JSON.stringify(chatHistory));
                
                return aiResponse;
            } catch (error) {
                console.error('API调用异常:', error);
                return `服务暂时不可用: ${error.message}`;
            }
        }

        async function askQuestion() {
            const question = document.getElementById('qa-input').value;
            if (!question) return;
            
            const chatDiv = document.getElementById('qa-chat');
            chatDiv.innerHTML += `<div class="user-question">${question}</div>`;
            
            document.getElementById('qa-input').value = '';
            document.getElementById('qa-input').disabled = true;
            
            try {
                chatDiv.innerHTML += `<div class="ai-loading">思考中...</div>`;
                const response = await getDeepSeekResponse(question);
                document.querySelector('.ai-loading').remove();
                chatDiv.innerHTML += `<div class="ai-answer">${response}</div>`;
            } catch (error) {
                document.querySelector('.ai-loading')?.remove();
                chatDiv.innerHTML += `<div class="ai-error">请求出错: ${error.message}</div>`;
                console.error('问答流程出错:', error);
            } finally {
                document.getElementById('qa-input').disabled = false;
                document.getElementById('qa-input').focus();
                chatDiv.scrollTop = chatDiv.scrollHeight;
            }
        }

        async function askQuestion() {
            const question = document.getElementById('qa-input').value;
            if (!question) return;
            
            const chatDiv = document.getElementById('qa-chat');
            chatDiv.innerHTML += `<div class="user-question">${question}</div>`;
            
            document.getElementById('qa-input').value = '';
            document.getElementById('qa-input').disabled = true;
            
            const response = await getSiliconFlowResponse(question);
            chatDiv.innerHTML += `<div class="ai-answer">${response}</div>`;
            chatDiv.scrollTop = chatDiv.scrollHeight;
            
            document.getElementById('qa-input').disabled = false;
            document.getElementById('qa-input').focus();
        }
        
        function clearHistory() {
            localStorage.removeItem('qa_history');
            document.getElementById('qa-chat').innerHTML = '';
            alert('对话历史已清空');
        }
        }
        const apiKey = "sk-a7e7579f109843fc9715ae79bbca2ed3";
        const apiUrl = "https://api.deepseek.com/v1/chat/completions";

        function openQAModal() {
            document.getElementById('qa-modal').style.display = 'block';
        }

        function closeQAModal() {
            document.getElementById('qa-modal').style.display = 'none';
        }

        async function askQuestion() {
            const question = document.getElementById('qa-input').value;
            if (!question) return;
            
            const chatDiv = document.getElementById('qa-chat');
            chatDiv.innerHTML += `<div class="user-question">${question}</div>`;
            
            try {
                chatDiv.innerHTML += `<div class="ai-loading">思考中...</div>`;
                const response = await getDeepSeekResponse(question);
                document.querySelector('.ai-loading').remove();
                chatDiv.innerHTML += `<div class="ai-answer">${response}</div>`;
            } catch (error) {
                document.querySelector('.ai-loading').remove();
                chatDiv.innerHTML += `<div class="ai-error">服务暂时不可用</div>`;
                console.error('问答出错:', error);
            }
            chatDiv.scrollTop = chatDiv.scrollHeight;
        }

        async function getDeepSeekResponse(question) {
            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: "deepseek-chat",
                        messages: [{role: "user", content: question}],
                        temperature: 0.7
                    })
                });

                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status}`);
                }

                const data = await response.json();
                return data.choices[0].message.content;
            } catch (error) {
                console.error('API调用错误:', error);
                throw error;
            }
        }
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM fully loaded');
            const qaButton = document.getElementById('qa-trigger');
            if (qaButton) {
                qaButton.addEventListener('click', openQAModal);
                console.log('QA button event listener added');
            } else {
                console.error('QA button element not found');
            }
        });
    </script>

    <footer>
        <p>© 2025 珠海科技学院 版权所有</p>
    </footer>
</body>
</html>